<template>
  <div class="home">
    <h2>App1 - Home Page</h2>
    
    <div class="info-section">
      <h3>从主应用接收的用户信息：</h3>
      <p>用户名：{{ userInfo?.name }}</p>
      <p>年龄：{{ userInfo?.age }}</p>
    </div>
    
    <div class="interaction-section">
      <h3>修改用户信息：</h3>
      <div class="form-group">
        <label>用户名：</label>
        <input v-model="newUserName" type="text" />
      </div>
      <div class="form-group">
        <label>年龄：</label>
        <input v-model="newUserAge" type="number" />
      </div>
      <button @click="updateUserInfo">更新用户信息（传递给主应用）</button>
    </div>
    
    <div class="tips">
      <p>💡 提示：修改用户信息后，切换到其他子应用，查看数据是否同步更新</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 用户信息
const userInfo = ref<any>(null)
const newUserName = ref('')
const newUserAge = ref<number | null>(null)

// 获取全局状态
const getGlobalState = () => {
  const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
  if (globalState) {
    userInfo.value = globalState.userInfo
    if (userInfo.value) {
      newUserName.value = userInfo.value.name
      newUserAge.value = userInfo.value.age
    }
  }
}

// 更新用户信息并通知主应用
const updateUserInfo = () => {
  if (newUserName.value && newUserAge.value) {
    const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
    if (globalState?.actions) {
      // 使用actions更新全局状态
      globalState.actions.setGlobalState({
        userInfo: {
          name: newUserName.value,
          age: newUserAge.value
        }
      })
      
      // 也可以直接调用主应用传递的回调函数
      if (globalState.onChangeUserInfo) {
        globalState.onChangeUserInfo({
          name: newUserName.value,
          age: newUserAge.value
        })
      }
    }
  }
}

// 设置全局状态变化监听
const setupGlobalStateListener = () => {
  const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
  if (globalState?.actions) {
    console.log('设置全局状态变化监听器')
    
    // 使用qiankun提供的onGlobalStateChange API监听状态变化
    return globalState.actions.onGlobalStateChange((state: any, prevState: any) => {
      console.log('全局状态变化:', state, prevState)
      if (state.userInfo && JSON.stringify(state.userInfo) !== JSON.stringify(userInfo.value)) {
        userInfo.value = { ...state.userInfo }
        if (userInfo.value) {
          newUserName.value = userInfo.value.name
          newUserAge.value = userInfo.value.age
        }
      }
    }, true) // true表示立即执行一次回调
  }
  return () => {}
}

onMounted(() => {
  console.log('HomeView组件挂载')
  getGlobalState()
  const cleanup = setupGlobalStateListener()
  
  // 组件卸载时清理监听器
  onUnmounted(() => {
    cleanup()
  })
})

// 监听路由变化
watch(() => router.currentRoute.value, (newRoute) => {
  console.log('App1路由变化:', newRoute.path)
})
</script>

<style scoped>
.home {
  padding: 20px;
}

h2 {
  color: #42b883;
  margin-bottom: 20px;
}

.info-section,
.interaction-section {
  background-color: #f8f8f8;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 8px;
}

h3 {
  margin-top: 0;
  color: #333;
}

.form-group {
  margin-bottom: 10px;
}

label {
  display: inline-block;
  width: 80px;
}

input {
  padding: 5px;
  width: 200px;
}

button {
  padding: 8px 15px;
  background-color: #42b883;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

button:hover {
  background-color: #3aa374;
}

.tips {
  background-color: #e3f2fd;
  padding: 10px;
  border-radius: 4px;
  font-size: 14px;
  color: #1976d2;
}
</style>